import SessionUtil, { JxbHttpClient } from '../../../data/session/session'
const Common = require('../../../utils/common.js');
let pageSize = getApp().data.pageSize1;

Page({
    data: {
        token: '',
        ItemList: {},
        by_volume: '',
        by_volumes: '../../images/sp_05.png',
        by_price: '',
        by_prices: '../../images/sp_05.png',
        productsList: {},
        chosenNum: 1,
        pageNo: 1,
        name: '',
        Type: '',
        categoryId: '',
        flavorId: '',
        purposeId: '',
        priceRangeId: '',
        isloading: true,
        nomore: false,
        moretext: "加载更多",
        singleStock: "",
        has_Filter: false,
        has_Filters: '../../images/sp_07.png',
        isShowShoppingchart: false,
        isShowChartChange: false,
        productMaskClass: "",
        tagValues: 0,
        Details: true,
    },
    onLoad: function (options) {
        // 页面初始化 options为页面跳转所带来的参数
        SessionUtil.getInstance().then(session=>{
            let server = session.getTheSellingServerSync(), user = session.getTheSessionUserSync()
            let brandId = options.brand_id,
                tagValue = wx.getStorageSync('tagValue'),
                renderData = {
                    pageNo: 1,
                    ItemList: {},
                    tagValues: 0,
                    brandId: brandId
                }
            if(tagValue) renderData.name = tagValue
            renderData.userid = user.userId
            var filter = wx.getStorageSync('Filter');
            if (filter) {
                renderData.categoryId = filter.categoryId
                renderData.flavorId = filter.flavorId
                renderData.purposeId = filter.purposeId
                renderData.priceRangeId = filter.priceRangeId
                if (filter.categoryId || filter.flavorId || filter.purposeId || filter.priceRangeId) {
                    renderData.has_Filter = true
                    renderData.has_Filters = '../../images/sp_08.png'
                } else {
                    renderData.has_Filter = false
                    renderData.has_Filters = '../../images/sp_07.png'
                }
            }
            this.setData(renderData);
            this.getBrandDetail(brandId);
            this.ItemList();
            wx.setNavigationBarTitle({
                title: server.getTheAgentSync().showName + '酒库',
            })
        })
    },
    onShow: function () {
        this.setData({
            tagValues: this.data.tagValues + 1,
        });
        var page = this;
        var name = wx.getStorageSync('tagValue'),
            userid = wx.getStorageSync('user_id');
        page.setData({
            userid: userid
        })

        if (this.data.tagValues <= 1 || name) {
            if (this.data.Details) {
                this.setData({
                    name: name ? name : '',
                    pageNo: 1,
                    ItemList: {},
                });
                if (name) {
                    this.setData({
                        tagValues: 0,
                    });
                }
                this.ItemList();
            } else {
                this.setData({
                    Details: true,
                    tagValues: 0,
                });
            }
        }
        var if_refresh = wx.getStorageSync("if_refresh");
        if (if_refresh == 5) {
            wx.removeStorageSync("Filter");
            page.setData({
                name: "",
                pageNo: 1,
                Type: "",
                categoryId: "",
                flavorId: "",
                purposeId: "",
                priceRangeId: "",
                specialString: "",
                by_volumes: '../../images/sp_05.png',
                by_prices: '../../images/sp_05.png',
                has_Filters: '../../images/sp_07.png',
            })
            this.ItemList();
        }
        //加载购物车
        page.productsLists();
    },
    onHide: function () {
        wx.removeStorageSync("tagvalue");
         this.setData({
            isShowChartChange:false
        })
    },
    onUnload: function () {
        wx.removeStorageSync("Filter");
    },
    updateSearchKey: function (e) {
        if (e.detail.value) {
            this.setData({
                name: e.detail.value
            })
        }
    },
    goCarts: function () {
        wx.switchTab({
            url: '/pages/shoppingcart/index'
        })
    },
    getBrandDetail: function (id) {
        var page = this;
        Common.my_request({
            url: '/AppMaster/BrandInfo/brandDetail',
            data: {
                brand_id: id
            },
            success: function (res) {
                if (res.data.result == 0) {
                    page.setData({
                        brandDetail: res.data.data
                    })
                }
            }
        });
    },

    /**关闭加入购物车弹窗 */
    hideCartpop: function (e) {
        this.setData({
            isShowChartChange: false
        })
    },
    // 更新搜索关键词
    goSearch: function (e) {
        var page = this;
        var KEY = page.data.name;
        this.setData({
            pageNo: 1,
            tagValues: 0,
        })
        wx.setStorageSync('tagValue', this.data.name);
        this.ItemList();
    },
    ItemList: function (action = '') {
        // 产品列表
        wx.showLoading({
            title: '数据加载中',
        })
        var page = this;
        var nowData = page.data.ItemList;
        var newData = {};
        var pageNo = page.data.pageNo;
        var name = page.data.name;
        var Type = page.data.Type;
        var categoryId = page.data.categoryId;
        var flavorId = page.data.flavorId;
        var purposeId = page.data.purposeId;
        var priceRangeId = page.data.priceRangeId;
        page.setData({
            isloading: false,
            moretext: "加载更多",
            nomore: true
        });
        //加载购物车
        page.productsLists();
        console.log(pageNo)
        if (pageNo < 1) {
            page.setData({
                isloading: true,
                nomore: false,
                moretext: "没有更多了"
            });
            wx.hideLoading();
            return;
        }

        Common.my_request({
            url: '/AppMaster/Item/ItemList',
            data: {
                pageSize: pageSize,
                pageNo: pageNo,
                name: name,
                type: Type,
                categoryId: categoryId,
                flavorId: flavorId,
                purposeId: purposeId,
                priceRangeId: priceRangeId,
                brandId: page.data.brandId
            },
            success: function (res) {
                console.log(res);
                if (res.data.result == 0) {

                    pageNo++;

                    if (res.data) {
                        var Lists = res.data.data.list;
                        if (Lists.length) {
                            var newData = Lists;
                        } else {
                            pageNo = -100;
                            page.setData({
                                isloading: true,
                                nomore: false,
                                moretext: "没有更多了"
                            });
                        }
                    }


                    if (action == 'Refresh') {
                        console.log('is Refresh!');
                        page.productsLists();
                        wx.stopPullDownRefresh();
                    } else if (action == 'Page') {
                        console.log('is Page!');
                        if (nowData.length) {
                            var newData = nowData.concat(Lists)
                        } else {
                            var newData = Lists
                        }
                    }
                    page.setData({
                        ItemList: newData,
                        pageNo: pageNo,
                        isloading: true,
                        nomore: false,
                    });

                    // 关闭加载
                    wx.hideLoading();


                } else {
                    console.log(res.data.message);
                    Common.if_login2(res.data.message);
                }

            }
        });
    },
    onPullDownRefresh: function () {
        var page = this;
        page.setData({
            ItemList: {},
            pageNo: 1
        });
        page.ItemList('Refresh');
        wx.stopPullDownRefresh();
    },
    onReachBottom: function () {
        var page = this;
        var pageNo = page.data.pageNo;
        page.setData({
            pageNo: pageNo
        });
        page.ItemList('Page');
    },
    OrderBy: function (e) {
        // console.log(e);
        // console.log(e.currentTarget.id);
        var page = this;
        var ID = e.currentTarget.id;
        var by_volume = page.data.by_volume;
        var by_price = page.data.by_price;

        /*
            序规则:
            1 = 销量顺序
            2 = 销量倒序
            3 = 单价顺序
            4 = 单价倒序
            0 = 默认
        */

        if (ID == 'volume') {
            console.log('volume');
            if (by_volume == '') {
                page.setData({
                    by_volume: 'down',
                    by_volumes: '../../images/sp_02.png',
                    by_price: '',
                    by_prices: '../../images/sp_05.png',
                    Type: 2
                });
            } else if (by_volume == 'down') {
                page.setData({
                    by_volume: 'up',
                    by_volumes: '../../images/sp_03.png',
                    by_price: '',
                    by_prices: '../../images/sp_05.png',
                    Type: 1
                });
            } else if (by_volume == 'up') {
                page.setData({
                    by_volume: '',
                    by_volumes: '../../images/sp_05.png',
                    by_price: '',
                    by_prices: '../../images/sp_05.png',
                    Type: 0
                });
            }
        } else if (ID == 'price') {
            console.log('price');
            if (by_price == '') {
                page.setData({
                    by_volume: '',
                    by_volumes: '../../images/sp_05.png',
                    by_price: 'down',
                    by_prices: '../../images/sp_02.png',
                    Type: 4
                });
            } else if (by_price == 'down') {
                page.setData({
                    by_volume: '',
                    by_volumes: '../../images/sp_05.png',
                    by_price: 'up',
                    by_prices: '../../images/sp_03.png',
                    Type: 3
                });
            } else if (by_price == 'up') {
                page.setData({
                    by_volume: '',
                    by_volumes: '../../images/sp_05.png',
                    by_price: '',
                    by_prices: '../../images/sp_05.png',
                    Type: 0
                });
            }
        }

        page.setData({
            pageNo: 1
        });

        page.ItemList();

    },
    goDetail: function (e) {
        var itemId = e.currentTarget.id;
        this.setData({
            Details: false,
        })
        wx.navigateTo({
            url: '/pages/product/detail/detail?itemId=' + itemId
        })
    },
    cancelCart: function () {
        var page = this;
        var isShowChartChange = page.data.isShowChartChange;
        var bIsisShowChartChange = isShowChartChange ? false : true;
        page.setData({
            isShowChartChange: bIsisShowChartChange,
            productMaskClass: bIsisShowChartChange ? "product-mask" : "",
        });
    },
    goFilter: function () {
        var page = this;
        wx.navigateTo({
            url: '/pages/product/filter/filter'
        })
    },
    AddCart: function (e) {
        var page = this;
        page.productsLists();
        var ID = e.currentTarget.id
        var itemId = ID.split('-')[0];
        var stock = ID.split('-')[1];
        var chosenItem;
        var insideNum = 0;
        var thisStock;
        var thislist;
        var acartid;

        page.setData({
            list_year: 0
        })

        // 显示年份
        Common.my_request({
            url: '/AppMaster/Item/getItemYearsList',
            data: {
                item_id: itemId
            },
            success: function (res) {
                if (res.data.result == 0) {
                    var normalInfo = res.data.data.item_info;
                    var list_year = res.data.data.item_year_list;
                    var activity = normalInfo.activity_category;
                    if (activity != 0) {
                        activity = activity.split(",");
                    }
                    page.setData({
                        chosenItem: normalInfo,
                        list_year: list_year,
                        activity: activity
                    })
                }
            }
        })

        page.setData({
            isShowChartChange: true,
            chosenNum: 1,
            singleStock: thisStock,
            sitemId: itemId,
            oldNum: insideNum,
            thisCartid: acartid
        });
    },
    // 点击年份切换商品
    changeYear: function (e) {
        var page = this;
        var itemId = e.currentTarget.id;
        var list_year = page.data.list_year;
        var chosenItem = page.data.chosenItem;
        if (chosenItem.item_id == itemId) {
            return false;
        } else {
            console.log(list_year)
            for (var i = 0; i < list_year.length; i++) {
                if (itemId == list_year[i].item_id) {
                    var activity = list_year[i].activity_category;
                    if (activity != 0) {
                        activity = activity.split(",");
                    }
                    page.setData({
                        chosenItem: list_year[i],
                        sitemId: itemId,
                        activity: activity
                    })
                }
            }
        }
    },

    goCart: function () {
        var page = this;
        var num = page.data.chosenNum;//输入框的数量
        num = parseInt(num);
        Common.my_request({
            url: '/AppMaster/PosCart/PosAddCart',
            data: {
                number: num,
                itemId: page.data.sitemId
            },
            success: function (res) {
                console.log(res)
                if (res.data.result == 0) {
                    wx.showToast({
                        title: '添加成功',
                        icon: 'success',
                        duration: 2000
                    })
                    page.productsLists();
                    page.cancelCart();
                    page.setData({
                        chosenNum: 0
                    })
                } else {
                    wx.showToast({
                        title: res.data.message,
                        image: '../../images/fail.png',
                        duration: 2000
                    })
                }
            }
        })
    },
    reduceSingle: function () {
        var page = this;
        var num = page.data.chosenNum - 1;
        if (num <= 1) {
            page.setData({
                chosenNum: 1,
            })
        } else {
            page.setData({
                chosenNum: num,
            })
        }
    },
    addToCartSingle: function () {
        var page = this;
        var stock = page.data.singleStock;
        var num = page.data.chosenNum + 1;
        if (num >= stock) {
            wx.showToast({
                title: '库存不足！',
                image: '../../images/fail.png',
                duration: 2000
            })
        } else {
            page.setData({
                chosenNum: num,
            })
        }
    },
    toZero: function (e) {
        var num = e.detail.value;
        if (num.length == 0) {
            this.setData({
                chosenNum: 1
            })
        }
    },
    updateNum: function (e) {
        var num = e.detail.value;
        var tnum = parseInt(num);
        this.setData({
            chosenNum: tnum
        })
    },

    productsLists: function () {
        (new JxbHttpClient).get('/AppMaster/PosCart/cartDetail').then(jxbResp=>{
            let respData = jxbResp.data, products = respData.productsList, 
                list = jrespData.activity_list
            let total = 0, gross = 0.00;
            let itemids = [];
            let limits = [];
            for (let z = 0; z < list.length; z++) {
                if (list[z].activity_category == 6) {
                    itemids = itemids.concat(list[z].itemids);
                }
                if (list[z].activity_category == 4) {
                    limits = limits.concat(list[z].itemids);
                }
            }
            for (let i = 0; i < products.length; i++) {
                total = total + products[i].carNumber;
                gross = gross + products[i].carNumber * products[i].show_price;
                let z = Common.contains(itemids, products[i].itemid),
                    w = Common.contains(limits, products[i].itemid);
                if (z && w) {
                    products[i].activity_list = ['秒杀', '限购']
                } else {
                    if (z) {
                        products[i].activity_list = ['秒杀'];
                    }
                    if (w) {
                        products[i].activity_list = ['限购'];
                    }
                }
            }
            respData.total = total;
            respData.gross = gross.toFixed(2);
            respData.productsList = products;
            this.setData({
                productsList: respData,
            })
        }).catch(err=>{
            console.log(err)
            wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
              })
            this.setData({
                productMaskClass: "",
                productsList: {},
            })
        })
    },
    shoppingChartList: function () {
        var page = this;
        var isShowShoppingchart = page.data.isShowShoppingchart;

        var bIsShowShoppingchart = isShowShoppingchart ? false : true;
        page.setData({
            isShowChartChange: false,
            isShowShoppingchart: bIsShowShoppingchart,
            productMaskClass: bIsShowShoppingchart ? "product-mask" : ""
        })
    },

    shoppingCartAdd: function (e) {
        var page = this;

        var itemId = e.currentTarget.id;
        Common.my_request({
            url: '/AppMaster/PosCart/PosAddCart', //仅为示例，并非真实的接口地址
            data: {
                number: 1,
                itemId: itemId
            },
            success: function (res) {
                if (res.data.result == 0) {
                    page.productsLists();
                } else {
                    wx.showToast({
                        title: res.data.message,
                        image: '../../images/fail.png',
                        duration: 2000
                    })
                }
            }
        });
    },

    shoppingCartReduce: function (e) {
        var page = this;

        var itemId = e.currentTarget.id;

        var cartId = itemId.split('_')[0];

        var num = itemId.split('_')[1] - 1;

        if (num < 1) {
            Common.my_request({
                url: '/AppMaster/PosCart/PosDelete', //仅为示例，并非真实的接口地址
                data: {
                    cartId: cartId
                },
                success: function (res) {
                    if (res.data.result == 0) {
                        page.productsLists();
                    }
                }
            });
        } else {
            Common.my_request({
                url: '/AppMaster/PosCart/PosUpdate', //仅为示例，并非真实的接口地址
                data: {
                    number: num,
                    cartId: cartId
                },
                success: function (res) {
                    if (res.data.result == 0) {
                        page.productsLists();
                    }
                }
            });
        }

    },
    clearShoppingCart: function (e) {
        var page = this;

        Common.my_request({
            url: '/AppMaster/PosCart/PosDelMyCart', //仅为示例，并非真实的接口地址
            success: function (res) {
                page.setData({
                    productsList: [],
                    isShowShoppingchart: !page.data.isShowShoppingchart,
                    productMaskClass: '',
                })

                wx.showToast({
                    title: '购物车已清空',
                    icon: 'success',
                    duration: 2000
                })
            }
        });
    },
    goOrderConfirm: function () {
        var _this = this
        _this.productsLists();
        setTimeout(function () {
            if (!_this.data.productsList.productsList) {
                Common.Alert("提示", "亲，请先添加购物车!");
            } else {
                _this.clearStorageSync();
                var userid = _this.data.userid;
                if (userid < 0) {
                    wx.navigateTo({
                        url: '/pages/my/logintype/logintype?from=0'
                    });
                } else {
                    wx.navigateTo({
                        url: '/pages/product/orderConfirm/index'
                    });
                }
            }
        }, 500);
    },
    clearStorageSync: function () {
        wx.setStorageSync("dilivery", '');
        wx.setStorageSync("invoice", {});
        wx.setStorageSync("pay", {});
    },
})